package org.wesc.boot.webapi.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.wesc.boot.common.utils.DateUtil;
import org.wesc.boot.dao.redis.RedisConstants;
import org.wesc.boot.dao.redis.RedisTemplateService;

import java.time.LocalDateTime;

/**
 * 主要用于定时删除 Redis中 key为 wesc.redis.user.active 中已经过期的 score
 * @author Wesley
 */
@Slf4j
@Component
public class ActiveUserCleanTask {

    private RedisTemplateService redisTemplateService;

    @Autowired
    public void setRedisTemplateService(RedisTemplateService redisTemplateService) {
        this.redisTemplateService = redisTemplateService;
    }

    @Scheduled(fixedRate = 86400000)
    public void run() {
        try {
            double now = Double.parseDouble(DateUtil.formatFullTime(LocalDateTime.now()));
            this.redisTemplateService.zremoveRangeByScore(RedisConstants.ACTIVE_USERS_ZSET_PREFIX, 0, now);
            log.info("Scheduled to Delete Expired Active User");
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
